<?php

/**
 * @author
 * @copyright 2009
 */

class Session{


	/**
	 * Opens the default session.
	 * 
	 * @return void
	 */
	public function open($cookieName="TEST"){
		if(!$this->isOpened()){
			session_name($cookieName);
			session_start();
		}
	}

	/**
	 * Inspector
	 * 
	 * @return boolean
	 */
	public function isOpened(){
		return isset($_SESSION);
	}

	/**
	 * Saves given value under given key.
	 * 
	 * @param String $key
	 * @param String $value
	 * @return void
	 */
	public function save($key, $value)
	{
		if($this->isOpened())
			$_SESSION[$key] = $value;
	}

	/**
	 * Checks if given key is set and returns value of that key.
	 * 
	 * @param String $key
	 * @return false | String
	 */
	public function check($key)
	{
		if($this->isOpened() && isset($_SESSION[$key]))
			return $_SESSION[$key];
		return false;
	}

	public function destroy(){
		session_unset();
		session_destroy();
	}
	
	public function close(){
		session_write_close();
	}

}

class UserSession extends Session{
	
	public static $ID='ID',$MAIL="MAIL",$LEVEL="LEVEL";
	public static $LEVELS = array("MEMBER"=>'1',"ADMIN"=>'9');
	
	public function open(){
		parent::open("UserCookie");
	}
	
	public function save($id, $email, $level){
		parent::save(self::$ID,$id);
		parent::save(self::$MAIL,$email);
		parent::save(self::$LEVEL,$level);
	}
	
	public function check(){
		return (parent::check(self::$ID)!=false);
	}
	public function getId(){
		return parent::check(self::$ID);
	}
	public function getEmail(){
		return parent::check(self::$MAIL);
	}
	public function getLevel(){
		return parent::check(self::$LEVEL);
	}
	
}

class Captcha extends Session{

	private $_question;
	public static $ANSWER="ANSWER";

	public function open(){
		parent::open("HumanTest");
	}

	public function save(){
		$answer = $this->_generateMathQuestion();
		parent::save(self::$ANSWER,$answer);
	}
	
	public function check($answer){
		$a = parent::check(self::$ANSWER);
		if(!$a)
			echo "no session set";
		return ($a == $answer);
	}

	public function getQuestion(){
		return $this->_question;
	}

	private function _generateMathQuestion(){
		$numberOne = rand(1,10);
		$numberTwo = rand(1,10);

		$this->_question = $numberOne ." + ". $numberTwo;

		return $numberOne + $numberTwo;
	}

}

?>